package es.udc.pfc.davidparedes.model.mission;

import java.util.Calendar;
import java.util.List;

import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import es.udc.pfc.davidparedes.model.dao.GenericDaoHibernate;
import es.udc.pfc.davidparedes.model.userservice.TypeAndMillisDTO;

@Repository("missionDao")
public class MissionDaoHibernate extends
		GenericDaoHibernate<Mission, Long> implements MissionDao {
	
	@SuppressWarnings("unchecked")
	public List<Mission> findMissionsByDate(Long userProfileId, Calendar startDate, Calendar endDate) {
		return getSession()
				  .createQuery(
				  "SELECT t FROM Mission t WHERE "
				  + "t.vendor.userProfileId = :userProfileId AND "
				  + "t.start >= :startDate AND t.end <= :endDate ORDER BY t.start")
				  .setParameter("userProfileId", userProfileId)
				  .setCalendarDate("startDate", startDate)
				  .setCalendarDate("endDate", endDate)
				  .list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Mission> findStoreMissionsByDate(Long storeId,
			Calendar startDate, Calendar endDate) {
		return getSession()
				  .createQuery(
				  "SELECT m FROM Mission m WHERE "
				  + "m.store.storeId = :storeId AND "
				  + "m.start >= :startDate AND m.end <= :endDate ORDER BY m.start")
				  .setParameter("storeId", storeId)
				  .setCalendar("startDate", startDate)
				  .setCalendar("endDate", endDate)
				  .list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Mission> findStoreMissionsAtMoment(Long storeId,
			Calendar moment) {
		return getSession()
				  .createQuery(
				  "SELECT m FROM Mission m WHERE "
				  + "m.store.storeId = :storeId AND "
				  + "m.start <= :moment AND m.end >= :moment ORDER BY m.start")
				  .setParameter("storeId", storeId)
				  .setCalendar("moment", moment)
				  .list();
	}

	@SuppressWarnings("unchecked")
	public List<TypeAndMillisDTO> getVendorMissionsDuration(Long userProfileId, Calendar startDate,
			Calendar endDate) {
		return getSession()
				  .createQuery(
				  "SELECT m.type as type, sum(m.duration) as millis FROM Mission m WHERE "
				  + "m.vendor.userProfileId = :userProfileId AND "
				  + "m.start >= :startDate AND m.end <= :endDate "
				  + "GROUP BY m.type")
				  .setParameter("userProfileId", userProfileId)
				  .setCalendarDate("startDate", startDate)
				  .setCalendarDate("endDate", endDate)
				  .setResultTransformer(Transformers.aliasToBean(TypeAndMillisDTO.class))
				  //.setResultTransformer(new AliasToBeanResultTransformer((TypeAndMillisDTO.class))
				  .list();

	}

}
